package com.hd.trans.ui.adapter;


import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hd.trans.R;
import com.hd.trans.common.Constants;
import com.hd.trans.db.bean.TranslateRecord;
import com.hd.trans.framework.click.XClickUtil;
import com.hd.trans.widgets.ImageTextView;
import com.hd.trans.widgets.VoicePlayView;

import java.util.List;

/**
 * Author:  yang
 * Date:    2020/01/07 15:58
 * Desc:    文本翻译记录适配器
 */
public class RecordVoiceTwoAdapter extends BaseMultiItemQuickAdapter<TranslateRecord, BaseViewHolder> {

    private int mEditPosition = -1;//编辑item位置
    private int mAutoPlayPosition = -1;//自动播放item位置
    private boolean isVip = true;

    public void setIsVip(boolean isVip){
        this.isVip = isVip;
        notifyDataSetChanged();
    }

    public interface VoiceClickListener {

        void onMenuEditClick(View view, int position);

        void onMenuCopyClick(View view, int position);

        void onMenuFullScreenClick(View view, int position);

        void onMenuCollectClick(View view, int position);

        void onMenuShareClick(View view, int position);

        void onMenuDeleteClick(View view, int position);

        void onRetryClick(View view, int position);//重试(重新翻译)

        void onAutoClick(View view, int position);//自动点击

        void onVoicePlayClick(View view, int position);//播放

        void unlockAll();//解锁全部内容
    }

    private VoiceClickListener mVoiceClickListener;


    public RecordVoiceTwoAdapter(@Nullable List<TranslateRecord> data) {
        super(data);
        addItemType(0, R.layout.item_result_left_layout);//正
        addItemType(1, R.layout.item_result_right_layout);//逆

        // 先注册需要点击的子控件id（注意，请不要写在convert方法里）
        addChildClickViewIds(R.id.tv_unlock_all, R.id.view_voice, R.id.talk_layout, R.id.tool,R.id.menu_editor, R.id.menu_copy,
                R.id.menu_full_screen, R.id.menu_collect, R.id.menu_share, R.id.menu_delete);
        setOnItemChildClickListener(new OnItemChildClickListener() {

            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if(XClickUtil.isFastDoubleClick(view,XClickUtil.INTERVAL_MILLIS)){
                    return;
                }
                Log.w("position", position + "---");
                int id = view.getId();
                if (id == R.id.view_voice) {
                    if (mVoiceClickListener != null) {
                        mVoiceClickListener.onVoicePlayClick(view, position);
                    }
                } else if (id == R.id.menu_editor) {
                    if (mVoiceClickListener != null) {
                        mVoiceClickListener.onMenuEditClick(view, position);
                    }
                } else if (id == R.id.menu_copy) {
                    if (mVoiceClickListener != null) {
                        mVoiceClickListener.onMenuCopyClick(view, position);
                    }
                } else if (id == R.id.menu_full_screen) {
                    if (mVoiceClickListener != null) {
                        mVoiceClickListener.onMenuFullScreenClick(view, position);
                    }
                } else if (id == R.id.menu_collect) {
                    if (mVoiceClickListener != null) {
                        mVoiceClickListener.onMenuCollectClick(view, position);
                    }
                } else if (id == R.id.menu_share) {
                    if (mVoiceClickListener != null) {
                        mVoiceClickListener.onMenuShareClick(view, position);
                    }
                } else if (id == R.id.menu_delete) {
                    if (mVoiceClickListener != null) {
                        mVoiceClickListener.onMenuDeleteClick(view, position);
                    }
                } else if (id == R.id.talk_layout) {
                    if (mVoiceClickListener != null) {
                        if (mEditPosition != position) {
                            int oldPos = mEditPosition;
                            mEditPosition = position;
                            notifyItemChanged(oldPos);
                            notifyItemChanged(mEditPosition);
                        } else {
                            mEditPosition = -1;
                            notifyItemChanged(position);
                        }
                    }
                } else if (id == R.id.tool) {
                    if(TextUtils.isEmpty(getData().get(position).getContentTranslate())){
                        if (mVoiceClickListener != null) {
                            mVoiceClickListener.onRetryClick(view, position);
                        }
                    }else {
                        if (mVoiceClickListener != null) {
                            if (mEditPosition != position) {
                                int oldPos = mEditPosition;
                                mEditPosition = position;
                                notifyItemChanged(oldPos);
                                notifyItemChanged(mEditPosition);
                            } else {
                                mEditPosition = -1;
                                notifyItemChanged(position);
                            }
                        }
                    }
                } else if(id == R.id.tv_unlock_all){
                    if (mVoiceClickListener != null) {
                        mVoiceClickListener.unlockAll();
                    }
                }
            }
        });
    }

    @Override
    public void remove(int position) {
        super.remove(position);
        if (mEditPosition == position) {
            mEditPosition = -1;
        } else if (mEditPosition > position) {
            mEditPosition--;
        }
        if (mAutoPlayPosition == position) {
            mAutoPlayPosition = -1;
        } else if (mAutoPlayPosition > position) {
            mAutoPlayPosition--;
        }
    }

    /**
     * 列表清空
     */
    public void notifyDataClear() {
        mEditPosition = -1;
        mAutoPlayPosition = -1;
        notifyDataSetChanged();
    }

//    public int getEditPosition() {
//        return mEditPosition;
//    }
//
//    public int getAutoPlayPosition() {
//        return mAutoPlayPosition;
//    }

    public void setAutoPlayPosition(int position) {
        if (mAutoPlayPosition != position) {
//            int oldPos = mAutoPlayPosition;
            mAutoPlayPosition = position;
        }
    }

    public void setEditPosition(int position) {
        if (mEditPosition != position) {
            int oldPos = mEditPosition;
            mEditPosition = position;
            notifyItemChanged(oldPos);
            notifyItemChanged(mEditPosition);
        }
    }

    //设置监听接口
    public void setVoiceClickListener(VoiceClickListener voiceClickListener) {
        this.mVoiceClickListener = voiceClickListener;
    }

    //布局转换
    @Override
    protected void convert(BaseViewHolder helper, TranslateRecord item) {
        if (item != null) {
            final int realPosition = helper.getLayoutPosition() - getHeaderLayoutCount();
            //条目复用初始化清空内容
            helper.setText(R.id.text_1, "");
            helper.setText(R.id.text_2, "");
            switch (helper.getItemViewType()) {
                case 0://正
                    ((VoicePlayView) helper.getView(R.id.view_voice)).setIsNormal(false,false);
                    break;

                case 1://逆
                    ((VoicePlayView) helper.getView(R.id.view_voice)).setIsNormal(false,true);
                    break;
            }
            TextView text2 = helper.getView(R.id.text_2);
            if(isVip){
                text2.setSingleLine(false);
            }else {
                text2.setSingleLine(true);
                text2.setEllipsize(TextUtils.TruncateAt.END);
            }
            helper.setText(R.id.text_1, item.getContentOrig());
            helper.setVisible(R.id.tv_unlock_all, !isVip);

            //翻译状态
            switch (item.getTranslateState()) {

                case Constants.VOICE_RECORD_NORMAL:
                    helper.setText(R.id.text_2, item.getContentTranslate());
                    helper.setGone(R.id.view_voice, false);
                    break;

                case Constants.VOICE_RECORD_TRANSLATING:
                    helper.setGone(R.id.view_voice, true);
                    break;

                case Constants.VOICE_RECORD_FAILED:
                    break;
            }

            //自动播放语音
            if (mAutoPlayPosition == realPosition) {
                mAutoPlayPosition = -1;

                mVoiceClickListener.onAutoClick(helper.getView(R.id.view_voice),realPosition);
            }

            //是否处于编辑状态
            if (mEditPosition == realPosition) {
                helper.setGone(R.id.ly_menu, false);
            } else {
                helper.setGone(R.id.ly_menu, true);
            }

            ImageTextView collectView = helper.getView(R.id.menu_collect);
            Drawable collectDrawable = collectView.getCompoundDrawables()[1];
            //更新收藏状态
            if (item.getIsCollected()) {
                collectDrawable.setLevel(2);
            } else {
                collectDrawable.setLevel(1);
            }
            collectView.setCompoundDrawables(null, collectDrawable, null, null);
        }
    }

    private PopupWindow pop;
    private int newPosition;
    private int windowHeight;
    private int popupHeight;
    //依附view的高度
    private int viewHeight;

    private void measureHeight(View v) {
        //测量popupwindow高度
        v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        popupHeight = v.getMeasuredHeight();  //获取测量后的高度
    }

    public void setWindowHeight(int windowHeight) {
        this.windowHeight = windowHeight;
    }

    private void showPop(View view, int posstion) {
        newPosition = posstion;
        View v = LayoutInflater.from(getContext()).inflate(R.layout.voice_pop_item_layout, null);
        if (pop == null) {
            pop = new PopupWindow(getContext());
            pop.setContentView(v);
            pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            pop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            pop.setFocusable(true);
            pop.setOutsideTouchable(true);
            measureHeight(v);
            //顺便也测一下依附控件高度
            view.findViewById(R.id.tool).measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            viewHeight = view.findViewById(R.id.tool).getMeasuredHeight();
        }

        v.findViewById(R.id.item_1).setOnClickListener(new View.OnClickListener() {//编辑
            @Override
            public void onClick(View v) {
                if (mVoiceClickListener != null)
                    mVoiceClickListener.onMenuEditClick(view, newPosition);
                pop.dismiss();
            }
        });
        v.findViewById(R.id.item_2).setOnClickListener(new View.OnClickListener() {//复制
            @Override
            public void onClick(View v) {
                if (mVoiceClickListener != null)
                    mVoiceClickListener.onMenuCopyClick(view, newPosition);
                pop.dismiss();
            }
        });
        v.findViewById(R.id.item_3).setOnClickListener(new View.OnClickListener() {//分享
            @Override
            public void onClick(View v) {
                if (mVoiceClickListener != null)
                    mVoiceClickListener.onMenuShareClick(view, newPosition);
                pop.dismiss();
            }
        });
        v.findViewById(R.id.item_4).setOnClickListener(new View.OnClickListener() {//删除
            @Override
            public void onClick(View v) {
                if (mVoiceClickListener != null)
                    mVoiceClickListener.onMenuDeleteClick(view, newPosition);
                pop.dismiss();
            }
        });

        //创建长度为2的数组，分别记录指定view在屏幕的x 和 y轴
        int[] location = new int[2];
        // 获得指定view在屏幕的位置
        view.findViewById(R.id.tool).getLocationOnScreen(location);

        //判断view在屏幕Y轴离底部不够一个pop的高度
        if (windowHeight - popupHeight - viewHeight > location[1]) {
            //如果够就显示在底部
            pop.showAsDropDown(view.findViewById(R.id.tool));
        } else {
            pop.showAtLocation(view.findViewById(R.id.tool), 0, location[0], location[1] - popupHeight);
        }

    }

}
